<?php

namespace App\Http\Controllers\Mini;

use App\Models\Ads;
use App\Models\Categorys;
use App\Models\Collections;
use App\Models\Footprints;
use App\Models\UserInfos;
use App\Models\Users;
use App\Models\WordCategorys;
use App\Models\WordDownloadLogs;
use App\Models\Words;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class WordController extends Controller
{
    /**
     * 文档分类
     * @route api.word.wordCate
     */
    public function wordCate(Request $request){
        try{
            $lists = WordCategorys::getCascaderList();
            $fields = ['id','thumb','title','cate_pid','cate_id','view','download','format'];
            foreach ($lists as $k=>$v){//获取分类下的热门文档
                $lists[$k]['hot'] = Words::allLists(['cid'=>$v['value'],'status'=>1], $fields, null, 6, 'download');
                foreach ($lists[$k]['hot'] as $key=>$val){
                    $lists[$k]['hot'][$key]['view'] = strlen($val['view'])>=4 ? '999+' : $val['view'];
                    $lists[$k]['hot'][$key]['download'] = strlen($val['download'])>=4 ? '999+' : $val['download'];
                    $lists[$k]['hot'][$key]['cate_pid'] = WordCategorys::where('id',$val['cate_pid'])->value('name');
                    $lists[$k]['hot'][$key]['cate_id'] = WordCategorys::where('id',$val['cate_id'])->value('name');
                }
                //获取分类下的广告
                $params = [
                    'adsense_id' => 38,
                    'status' => 1,
                ];
                $lists[$k]['adv'] = Ads::getList($params, ['id','adsense_id','thumb','link','target']);
            }

            return response()->json([
                "code" => 1,
                "msg" => "获取成功",
                "data" => $lists
            ]);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 文档筛选
     * @route api.word.wordScreen
     */
    public function wordScreen(Request $request){
        try{
            $lists = WordCategorys::getCascaderList();

            return response()->json([
                "code" => 1,
                "msg" => "获取成功",
                "data" => $lists
            ]);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 文档列表
     * @route api.word.wordLists
     * @param content 热搜词条
     * @param cid_id 二级分类id
     * @param page 页码
     * @param limit 条数
     * @param sid 排序 1下载量 2浏览量
     */
    public function wordLists(Request $request){
        try{
            $cid_id = $request->post('cid_id');//二级分类id
            $cid_pid = $request->post('cid_pid');//一级分类id
            $map['keyword'] = $request->post('content');//热搜词条
            if (!empty($cid_pid)){
                $map['cid_pid'] = explode(",", $cid_pid);
            }else {
                $map['cid_pid'] = null;
            }
            if (!empty($cid_id)){
                $map['cid_id'] = explode(",", $cid_id);
            }else {
                $map['cid_id'] = null;
            }
            $page = (int)$request->post('page',1);//页码
            $limit = (int)$request->post('limit',5);//条数
            if (empty($page) || empty($limit)) return response()->json(["code"=>0, "msg"=>'参数错误']);
            $sid = (int)$request->post('sid');//排序 1下载量 2浏览量
            if ($sid == 1){
                $sort = 'download';
            }elseif ($sid == 2){
                $sort = 'view';
            }else{
                $sort = 'created_at';
            }
            $fields = ['id','thumb','title','cate_pid','cate_id','view','download','format','cate_pid','cate_id'];
            $lists = Words::allLists($map, $fields, $page, $limit, $sort, 'desc');
            foreach ($lists as $key=>$val){
                $lists[$key]['view'] = strlen($val['view'])>=4 ? '999+' : $val['view'];
                $lists[$key]['download'] = strlen($val['download'])>=4 ? '999+' : $val['download'];
                $lists[$key]['cate_pid'] = WordCategorys::where('id',$val['cate_pid'])->value('name');
                $lists[$key]['cate_id'] = WordCategorys::where('id',$val['cate_id'])->value('name');
            }

            return response()->json([
                "code" => 1,
                "msg" => "获取成功",
                "data" => $lists
            ]);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 文档详情
     * @route api.word.wordDetails
     * @param user_id 用户id
     * @param word_id 文档id
     * @return is_collect 0:未收藏 1:已收藏
     */
    public function wordDetails(Request $request){
        try{
            $user_id = (int)$request->post('user_id');
            $user_info = Users::where('id',$user_id)->where('status','<>',-1)->first();
            $word_id = (int)$request->post('word_id');//文档id
            if (empty($word_id)) return response()->json(["code"=>0, "msg"=>'参数错误']);

            $lists = Words::details(['id'=>$word_id]);
            $cate_pid_name = WordCategorys::where('id',$lists['cate_pid'])->value('name');
            $cate_id_name = WordCategorys::where('id',$lists['cate_id'])->value('name');
            if (!empty($cate_id_name)){
                $lists['cate'] = $cate_pid_name . '--' . $cate_id_name;
            }else{
                $lists['cate'] = $cate_pid_name;
            }

            $lists['view'] = strlen($lists['view'])>=4 ? '999+' : $lists['view'];
            $lists['download'] = strlen($lists['download'])>=4 ? '999+' : $lists['download'];
            $lists['created_at'] = trim(@date('Y-m-d', strtotime($lists['created_at'])));

            //判断是否收藏和报名
            $lists['is_collect'] = 0;//默认未收藏
            if (!empty($user_info)){
                if ($user_info['type'] == 1){
                    $collect = Collections::where(['collect_id'=>$word_id,'user_id'=>$user_info['id'],'type'=>1])->value('collect_id');
                    $lists['is_collect'] = empty($collect) ? 0 : 1;
                }
                //添加足迹
                $foot_arr = [
                    'user_id' => $user_info['id'],
                    'foot_id' => $word_id,
                    'type'    => 5,
                ];
                $foot_id = Footprints::where($foot_arr)->value('id');
                if($foot_id > 0){
                    Footprints::where($foot_arr)->update(['updated_at'=>date('Y-m-d H:i:s')]);
                }else{
                    Footprints::create($foot_arr);
                }
            }
            Words::where('id',$word_id)->increment('view');//浏览量加1

            $lists['hot'] = Words::allLists([], ['id','thumb','title','cate_pid','cate_id','view','download','format'], null, 2, 'download');
            foreach ($lists['hot'] as $key=>$val){
                $lists['hot'][$key]['view'] = strlen($val['view'])>=4 ? '999+' : $val['view'];
                $lists['hot'][$key]['download'] = strlen($val['download'])>=4 ? '999+' : $val['download'];
                $lists['hot'][$key]['cate_pid'] = WordCategorys::where('id',$val['cate_pid'])->value('name');
                $lists['hot'][$key]['cate_id'] = WordCategorys::where('id',$val['cate_id'])->value('name');
            }

            return response()->json([
                "code" => 1,
                "msg" => "获取成功",
                "data" => $lists
            ]);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 收藏文档
     * @route api.word.wordCollects
     * @param user_id 用户id
     * @param collect_id 收藏内容id
     */
    public function wordCollects(Request $request){

        try{
            $user_id = (int)$request->post('user_id');
            if (empty($user_id)) return response()->json(["code"=>0, "msg"=>'请先登录']);
            $userinfo = Users::where(['id'=>$user_id])->where('status','<>',-1)->first(['type','status']);
            if (empty($userinfo)){
                return response()->json(["code"=>0, "msg"=>'用户不存在,请联系客服!']);
            }else{
                if($userinfo['status'] == 2){
                    return response()->json(["code"=>0, "msg"=>'账户正在审核中，请等待审核!']);
                }elseif($userinfo['status'] == 3){
                    return response()->json(["code"=>0, "msg"=>'账号未通过审核，请前往个人中心查看原因并重新提交审核!']);
                }elseif ($userinfo['status'] == 4){
                    return response()->json(["code"=>0, "msg"=>'账号已锁定，请前往个人中心查看原因或联系客服!']);
                }
                if ($userinfo['type'] != 1) return response()->json(["code"=>0, "msg"=>'供应商不能收藏文档!']);
            }

            $collect_id = (int)$request->post('collect_id');
            if (empty($collect_id)) return response()->json(["code"=>0, "msg"=>'参数错误']);

            $collect = Collections::where(['collect_id'=>$collect_id, 'user_id'=>$user_id, 'type'=>1])->value('id');
            if (empty($collect)){
                $params = [
                    'collect_id' => $collect_id,
                    'user_id' => $user_id,
                    'collect_at' => date('Y-m-d H:i:s'),
                    'type' => 1,
                ];
                Collections::create($params);
                Words::where('id',$collect_id)->increment('collect');
                return response()->json(["code"=>1, "msg"=>'收藏成功']);
            }else {
                Collections::where(['collect_id'=>$collect_id, 'user_id'=>$user_id, 'type'=>1])->delete();
                return response()->json(["code"=>1, "msg"=>'取消收藏成功']);
            }
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

    /**
     * 文档下载
     * @param url home.word.wordDownload
     * @param user_id 用户id
     * @param word_id 文档id
     * @return bool
     */
    public function wordDownload(Request $request){
        try{
            $user_id = (int)$request->post('user_id');
            if (empty($user_id)) return response()->json(["code"=>0, "msg"=>'请先登录']);
            $userinfo = Users::where(['id'=>$user_id])->where('status','<>',-1)->first(['nickname','type','status']);
            if (empty($userinfo)){
                return response()->json(["code"=>0, "msg"=>'用户不存在,请联系客服!']);
            }else{
                if($userinfo['status'] == 2){
                    return response()->json(["code"=>0, "msg"=>'账户正在审核中，请等待审核!']);
                }elseif($userinfo['status'] == 3){
                    return response()->json(["code"=>0, "msg"=>'账号未通过审核，请前往个人中心查看原因并重新提交审核!']);
                }elseif ($userinfo['status'] == 4){
                    return response()->json(["code"=>0, "msg"=>'账号已锁定，请前往个人中心查看原因或联系客服!']);
                }
                if ($userinfo['type'] != 1) return response()->json(["code"=>0, "msg"=>'供应商不能下载文档!']);
                $more = UserInfos::where('user_id',$user_id)->value('company_name');
                if ($more == null) return response()->json(["code"=>0, "msg"=>'您还未完善信息，请前往个人中心完善信息后再发布!']);
            }

            $word_id = (int)$request->post('word_id');
            if (empty($word_id)) return response()->json(["code"=>0, "msg"=>'参数错误']);
            $params = [
                'word_id' => $word_id,
                'user_id' => $user_id,
            ];
            WordDownloadLogs::create($params);
            Words::where('id',$word_id)->increment('download');//下载量加1
            $link = Words::where('id',$word_id)->value('file_link');
            return response()->json(["code"=>1, "msg"=>'下载成功','data'=>$link]);
        }catch (\Exception $e){
            return response()->json(["code"=>0, "msg"=>$e->getMessage()]);
        }
    }

}